var thisPage = {
    _leaveApplicationId: "",
    _taskId: "",
    _pageStatus: "0", //"1":新增；"2":编辑
    // 初始化页面
    OnPageLoad: function () {
        if (parseInt(thisPage._pageStatus) === 2) {
            thisPage.FetchByKey();
        } else {
            thisPage.New();
        }
    },
    FetchByKey: function () {
        var _params = {};
        _params['LeaveApplicationId'] = thisPage._leaveApplicationId;
        $.ajax({
            type: "POST",
            url: parent.basePath + "/hr/leave_application/fetchByKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify(_params),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            $("#ButStart").hide();
            $("#ButReApply").hide();
            let _item = data.LeaveApplicationEntity;
            thisPage._leaveApplicationId = _item.leaveApplicationId;
            thisPage._taskId = _item.taskId;
            // 重新申请
            if (_item.flowNodeKey === "modifyapply") {
                $("#ButReApply").show();
            }
            // 销假
            if (_item.flowNodeKey !== "reportback") {
                $("#reportback").hide();
            }

            $("#LeaveApplicationType").val(_item.leaveApplicationTypeId);
            $("#StartTime").val(_item.startTime);
            $("#EndTime").val(_item.endTime);
            $("#Reason").val(_item.reason);

            if (data.ProcApproveComment !== null) {
                thisPage.ShowApproveComment(data.ProcApproveComment);
            }

            $("#LeaveApplicationType").focus();
        }).fail(function (data) {
            $('#loading').hide();
            ajaxError(data, 1);
        }).always(function () {
            $('#loading').hide();
        });
    },
    New: function () {
        $("#form_data").data("changed", false);   // 重新初始化

        // 清空表单内容，准备下一个记录
        $(':input', '#form_data').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $('#form_data')[0].reset();
        $(".error").removeClass("error");
        $(".tooltip").remove();
        $("img.errMsgTooltip").remove();
        $('#form_data span.selectSpan').html('');

        // 默认设置一些值
        $("#StartTime").val(getCurrentDate());
        $("#EndTime").val(getCurrentDate());

        thisPage._pageStatus = "1";
        $("div.accordion-container").hide();
        $("#ButReApply").remove();

        $("#LeaveApplicationType").focus();
        $('#loading').hide();
    },
    // 得到请假单
    GetEntityData() {
        let item = {};
        item['leaveApplicayionId'] = $("#LeaveApplicayionId").val();
        item['userId'] = parseInt(parent.$("#UserId").val());
        item['userName'] = parent.$("#UserName").val();
        item['leaveApplicationTypeId'] = $.trim($("#LeaveApplicationType").val());   // 类型
        item['startTime'] = $.trim($("#StartTime").val());                           // 开始时间
        item['endTime'] = $.trim($("#EndTime").val());                               // 结束时间
        item['reason'] = formatNullInputValue($.trim($("#Reason").val()));           // 事由
        item['createdBy'] = parseInt(parent.$("#UserId").val());
        item['updatedBy'] = parseInt(parent.$("#UserId").val());

        let _params = parent._Instance.SetCriterion({});
        _params['LeaveApplicationEntity'] = item;

        return JSON.stringify(_params);
    },
    // 保存数据
    Start: function () {
        // step 1、进行页面验证，失败则返回
        if (!$("#form_data").valid())
            return;
        // step 2、设置结果（保存成功后，刷新日历）
        $.ajax({
            type: "POST",
            url: parent.basePath + "/hr/leave_application/start.html",
            timeout: 30 * 1000,
            data: thisPage.GetEntityData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            // 新建
            if (parseInt(thisPage._pageStatus) === 1) {
                parent.ShowSuccessMessagePanel("请假申请成功。");
                thisPage._pageStatus = "2";
            } else {  // 编辑
                if (data.Success) {
                    parent.ShowSuccessMessagePanel("请假申请成功。");
                } else {
                    parent.ShowErrorMessagePanel('请假申请失败。');
                }
            }
            // 刷新父窗口数据
            parent._Instance.FetchForPage(parent._Instance.$pagination.attr("_msh_page"));
            // 关闭对话框
            closePopupWnd();
        }).fail(function (data) {
            $('#loading').hide();
            ajaxError(data, 1);
        }).always(function () {
            $('#loading').hide();
        });
    },
    ShowApproveComment: function (result) {
        $("#tabDataComment tbody").empty();
        let content_01 = '';
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].taskId + '">';
            content_01 += '<td>' + result[i].taskName + '</td>';
            content_01 += '<td>' + result[i].assigneeName + '</td>';
            content_01 += '<td>' + formatNullData(result[i].endTime) + '</td>';
            content_01 += '<td style="border-right:none;">' + formatNullData(result[i].approveComment) + '</td>';
            content_01 += '</tr>';

            $("#tabDataComment tbody").append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabDataComment");
    },
    // 销假
    End: function () {
        var item = {};
        item['leaveApplicationId'] = thisPage._leaveApplicationId;
        item['taskId'] = thisPage._taskId;
        item['realStartTime'] = $.trim($("#RealStartTime").val());              // 开始时间
        item['realEndTime'] = $.trim($("#RealEndTime").val());                  // 结束时间
        item['createdBy'] = parseInt(parent.$("#UserId").val());
        item['updatedBy'] = parseInt(parent.$("#UserId").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + "/hr/leave_application/end.html",
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data > 0) {
                parent.ShowSuccessMessagePanel("销假成功。");
            } else {
                parent.ShowErrorMessagePanel('销假失败。');
            }
            // 刷新父窗口数据
            parent._Instance.FetchForPage(parent._Instance.$pagination.attr("_msh_page"));
            // 关闭对话框
            closePopupWnd();
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
        });
    },
    // 调整申请
    ReApply: function () {
        var item = {};
        item['leaveApplicationId'] = thisPage._leaveApplicationId;
        item['taskId'] = thisPage._taskId;
        item['startTime'] = $.trim($("#StartTime").val());                      // 开始时间
        item['endTime'] = $.trim($("#EndTime").val());                          // 结束时间
        item['reason'] = formatNullInputValue($.trim($("#Reason").val()));      // 事由
        item['reapply'] = true;                                                 // 重新申请
        item['createdBy'] = parseInt(parent.$("#UserId").val());
        item['updatedBy'] = parseInt(parent.$("#UserId").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + "/hr/leave_application/reapply.html",
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data > 0) {
                parent.ShowSuccessMessagePanel("调整申请成功。");
            } else {
                parent.ShowErrorMessagePanel('调整申请失败。');
            }
            // 刷新父窗口数据
            parent._Instance.FetchForPage(parent._Instance.$pagination.attr("_msh_page"));
            // 关闭对话框
            closePopupWnd();
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
        });
    }
};
//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    thisPage._leaveApplicationId = jQuery.url.param("leaveApplicationId") === undefined ? "" : jQuery.url.param("leaveApplicationId");
    thisPage._pageStatus = jQuery.url.param("action") === undefined ? "0" : jQuery.url.param("action");
    $("#form_data").data("changed", false); // 初始化form数据提交状态

    window.laydate.render({
        elem: '#StartTime',
        type: 'date',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#EndTime',
        type: 'date',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#RealStartTime',
        type: 'date',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#RealEndTime',
        type: 'date',
        theme: '#393D49',
        trigger: 'click'
    });

    $(".accordion-set > span").on("click", function () {
        if ($(this).hasClass("active")) {
            $(this).removeClass("active");
            $(this).siblings(".accordion-content").slideUp(200);
            $(".accordion-set > span i").removeClass("fa-minus").addClass("fa-plus");
        } else {
            $(".accordion-set > span i").removeClass("fa-minus").addClass("fa-plus");
            $(this).find("i").removeClass("fa-plus").addClass("fa-minus");
            $(".accordion-set > span").removeClass("active");
            $(this).addClass("active");
            $(".accordion-content").slideUp(200);
            $(this).siblings(".accordion-content").slideDown(200);
        }
    });

    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _LeaveApplicationType: {
                valueNotEquals: "-1",
                required: true
            },
            _StartTime: {
                dateISO: true,
                required: true
            },
            _EndTime: {
                dateISO: true,
                required: true
            }
        },
        messages: {
            _LeaveApplicationType: {
                valueNotEquals: "请选择请假类型。",
                required: "请选择请假类型。"
            },
            _StartTime: {
                dateISO: "请填写正确的请假起始日期。",
                required: "请填写请假起始日期。"
            },
            _EndTime: {
                dateISO: "请填写正确的请假结束日期。",
                required: "请填写请假结束日期。"
            }
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});